package com.lagou.muticodec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.TooLongFrameException;
import io.netty.util.CharsetUtil;

import java.util.List;

import static io.netty.util.internal.ObjectUtil.checkPositive;

public class DtuDecoder extends ByteToMessageDecoder {

    private static final int ST_CORRUPTED = -1;
    private static final int ST_INIT = 0;
    private static final int ST_DECODING_NORMAL = 1;
    private static final int ST_DECODING_ARRAY_STREAM = 2;

    private int openBraces;
    private int idx;

    private int lastReaderIndex;

    private int state;
    private boolean insideString;
    private int frameIndex=0;
    private boolean fixedFrame=false;

    private ByteBuf buf = Unpooled.buffer(1);
    private byte fisrtByte='{';

    private final int maxObjectLength;
    private int fixedFrameLength;

    private final boolean streamArrayElements;

    public DtuDecoder() {
        // 1 MB
        this(1024 * 1024);
    }

    public DtuDecoder(int maxObjectLength) {
        this(maxObjectLength, false);
    }

    public DtuDecoder(boolean streamArrayElements) {
        this(1024 * 1024, streamArrayElements);
    }

    /**
     * @param maxObjectLength   maximum number of bytes a JSON object/array may use (including braces and all).
     *                             Objects exceeding this length are dropped and an {@link TooLongFrameException}
     *                             is thrown.
     * @param streamArrayElements   if set to true and the "top level" JSON object is an array, each of its entries
     *                                  is passed through the pipeline individually and immediately after it was fully
     *                                  received, allowing for arrays with "infinitely" many elements.
     *
     */
    public DtuDecoder(int maxObjectLength, boolean streamArrayElements) {
        this.maxObjectLength = checkPositive(maxObjectLength, "maxObjectLength");
        this.streamArrayElements = streamArrayElements;
    }

    public DtuDecoder(int maxObjectLength, int fixedFrameLength) {
        this(maxObjectLength, false);
        this.fixedFrameLength = fixedFrameLength;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (state == ST_CORRUPTED) {
            in.skipBytes(in.readableBytes());
            return;
        }

        if (this.idx > in.readerIndex() && lastReaderIndex != in.readerIndex()) {
            this.idx = in.readerIndex() + (idx - lastReaderIndex);
        }

        // index of next byte to process.
        int idx = this.idx;
        int wrtIdx = in.writerIndex();

        if (wrtIdx > maxObjectLength) {
            // buffer size exceeded maxObjectLength; discarding the complete buffer.
            in.skipBytes(in.readableBytes());
            reset();
            throw new TooLongFrameException(
                    "object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded");
        }
        for (/* use current idx */; idx < wrtIdx; idx++) {
            byte c = in.getByte(idx);
            //System.out.println("in.readerIndex():" + in.readerIndex());
            if (c == '{' && frameIndex == 0) {
                fisrtByte = c;
            }else if (c != '{' && frameIndex == 0) {
                fixedFrame=true;
            }
            frameIndex++;
            buf.writeByte(c);
            if (c == '}') {
                out.add(buf);
                //System.out.println("buf.toString(CharsetUtil.UTF_8):"+buf.toString(CharsetUtil.UTF_8));
                buf=Unpooled.buffer(0);
                //buf.clear();
                frameIndex = 0;
                fixedFrame=false;
            }
            if(fixedFrame && frameIndex==fixedFrameLength){
                //System.out.println("frameIndex:"+frameIndex);
                //System.out.println("fixedFrameLength:"+fixedFrameLength);
                out.add(buf);
                //System.out.println( "AlexUtil.bytesToHexString(buf.array()):"+ AlexUtil.bytesToHexString(buf.array()));
                buf=Unpooled.buffer(0);
                //buf.clear();
                frameIndex = 0;
                fixedFrame=false;
            }
        }
        in.skipBytes(in.readableBytes());
    }

    /**
     * Override this method if you want to filter the json objects/arrays that get passed through the pipeline.
     */
    @SuppressWarnings("UnusedParameters")
    protected ByteBuf extractObject(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) {
        return buffer.retainedSlice(index, length);
    }

    private void decodeByte(byte c, ByteBuf in, int idx) {
        if ((c == '{' || c == '[') && !insideString) {
            openBraces++;
        } else if ((c == '}' || c == ']') && !insideString) {
            openBraces--;
        } else if (c == '"') {
            // start of a new JSON string. It's necessary to detect strings as they may
            // also contain braces/brackets and that could lead to incorrect results.
            if (!insideString) {
                insideString = true;
            } else {
                int backslashCount = 0;
                idx--;
                while (idx >= 0) {
                    if (in.getByte(idx) == '\\') {
                        backslashCount++;
                        idx--;
                    } else {
                        break;
                    }
                }
                // The double quote isn't escaped only if there are even "\"s.
                if (backslashCount % 2 == 0) {
                    // Since the double quote isn't escaped then this is the end of a string.
                    insideString = false;
                }
            }
        }
    }

    private void initDecoding(byte openingBrace) {
        openBraces = 1;
        if (openingBrace == '[' && streamArrayElements) {
            state = ST_DECODING_ARRAY_STREAM;
        } else {
            state = ST_DECODING_NORMAL;
        }
    }

    private void reset() {
        insideString = false;
        state = ST_INIT;
        openBraces = 0;
    }
}

